import json
import requests

def read_json_data_from_file(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        json_data_list = file.read().splitlines()

    # 解析每一行 JSON 数据
    json_objects = []
    for json_data in json_data_list:
        try:
            json_object = json.loads(json_data)
            json_objects.append(json_object)
        except json.JSONDecodeError:
            print("Error decoding JSON data:", json_data)

    return json_objects


# 打开并加载JSON文件
def read_json_data_from_jsonfile(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        sql_statements = json.load(file)
    return sql_statements


def train(data):
    url = "http://127.0.0.1:5000/api/v0/train"
    # 发送POST请求
    response = requests.post(url, json=data)
    # 检查响应状态码
    if response.status_code == 200:
        # 打印响应内容
        print("Response:")
        print(response.text)
    else:
        print("Error:", response.status_code)


def main():
    try:
        # 读取多行文本文件中的 JSON 数据
        #json_objects = read_json_data_from_file('data/ddl.txt')

        # 读取 JSON 文件
        json_objects = read_json_data_from_jsonfile("./data/smartpole_ddl_2.json")
        # 输出每个 JSON 数据中的问题和SQL语句
        for index, json_object in enumerate(json_objects, start=1):
            ddl = json_object.get('ddl')
            print(f"Data {index}:")
            print("DDL:", ddl)
            print()
            train(json_object)


    except FileNotFoundError:
        print("Text file not found.")


if __name__ == "__main__":
    main()
